var models = require('../models');
var error = require('../util/error');
var utilString = require('../util/string');

exports.reg = function(req, res) {
	res.render('account/reg', {
		title: 'reg'
	});
}
exports.register = function(req, res) {
	var u = new models.User;
	u.name = req.body.name;
	u.email = req.body.email;
	u.password = req.body.password;
	u.save(function(err, user) {
		if(err) {
			res.send(500, err);
		} else {
			u.createCookie(res)
			res.end();
		}
	})
};
exports.sign = function(req, res) {
	res.render('account/sign', {
		title: 'reg'
	});
}
exports.signin = function(req, res) {
	var email = req.body.email;
	var password = req.body.password;
	password = utilString.md5(password);
	models.User.findOne({
		email: email,
		password: password
	}, function(err, user) {
		if(err) {
			res.send(500, err);
		}
		if(user) {
			user.createCookie(res)
		} else {
			res.send(401, {
				message: '用户名或密码错误'
			});
		}
		res.end();
	});
};